<template>
<el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px">
    <back-button></back-button>
    <!-- 标题 -->
    <h2>资产派发</h2>

    <!-- 基础信息 -->
    <div class="base-info">
        <span>基础信息</span>

        <!-- 表单项：标题 -->
        <el-form-item label="标题：" prop="title">
            <el-input v-model="ruleForm.title"></el-input>
        </el-form-item>

        <el-form-item label="状态" prop="state">
            <el-select v-model="ruleForm.state" placeholder="请选择状态">
                <el-option label="草稿" :value="0"></el-option>
                <el-option label="审核中" :value="1"></el-option>
                <el-option label="驳回" :value="2"></el-option>
                <el-option label="已办结" :value="3"></el-option>
            </el-select>
        </el-form-item>

        <!-- 表单项：申请单号、申请日期 -->
        <el-row type="flex" justify="space-between">
            <el-col :span="11">
                <el-form-item label="申请单号" prop="applicationNum">
                    <el-input v-model="ruleForm.applicationNum" disabled></el-input>
                </el-form-item>
            </el-col>
            <el-col :span="11">
                <el-form-item label="申请日期" prop="applicationDate">
                    <el-date-picker v-model="ruleForm.applicationDate" type="date" placeholder="选择日期" value-format="yyyy-MM-dd"></el-date-picker>
                </el-form-item>
            </el-col>
        </el-row>

        <!-- 表单项：申请人、申请部门 -->
        <el-row type="flex" justify="space-between">
            <el-col :span="11">
                <el-form-item label="申请人" prop="applicantId">
                    <el-select v-model="ruleForm.applicantId" placeholder="请选择" @focus="fetchApplicants">
                        <el-option v-for="applicant in applicants" :key="applicant.id" :label="applicant.name" :value="applicant.id"></el-option>
                    </el-select>
                </el-form-item>
            </el-col>
        </el-row>

        <!-- 表单项：领用日期 -->
        <el-form-item label="领用日期" prop="distributeDate">
            <el-date-picker v-model="ruleForm.distributeDate" type="date" placeholder="选择日期" value-format="yyyy-MM-dd"></el-date-picker>
        </el-form-item>

        <!-- 表单项：申请事由、备注 -->
        <el-row type="flex" justify="space-between">
            <el-col :span="24">
                <el-form-item label="派发事由" prop="distributeReason">
                    <el-input type="textarea" v-model="ruleForm.distributeReason"></el-input>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row type="flex" justify="space-between">
            <el-col :span="24">
                <el-form-item label="备注" prop="remark">
                    <el-input type="textarea" v-model="ruleForm.remark"></el-input>
                </el-form-item>
            </el-col>
        </el-row>
    </div>

    <div>
        <span>资产明细</span>
        <el-row>
            <el-button type="primary" @click="addAsset">添加</el-button>
            <el-button @click="removeAsset">移除</el-button>
        </el-row>
        <!-- 弹层组件，使用 v-if 控制显示 -->
        <asset-add v-if="showAssetDialog" @close="showAssetDialog = false" @data-submitted="handleData"></asset-add>

        <!-- 表格 -->
        <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column type="index" label="序号" :index="indexMethod"></el-table-column>
            <el-table-column prop="assetName" label="资产名称" width="180"></el-table-column>
            <el-table-column prop="number" label="资产编码" width="180"></el-table-column>
            <el-table-column prop="model" label="规格型号"></el-table-column>
            <el-table-column prop="kind" label="资产分类"></el-table-column>
            <el-table-column prop="unit" label="单位"></el-table-column>
            <el-table-column prop="adminName" label="管理人"></el-table-column>
            <el-table-column prop="userName" label="使用人"></el-table-column>
            <el-table-column prop="nowLocation" label="当前存放位置" width="120"></el-table-column>
            <el-table-column prop="targetLocation" label="领取后存放位置" width="120"></el-table-column>
            <el-table-column fixed="right" label="操作" width="120">
                <template slot-scope="scope">
                    <el-button @click.native.prevent="deleteRow(scope.$index, tableData)" type="text" size="small">移除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="block">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[7, 10, 15, 20]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </div>
    </div>

    <!-- 提交按钮 -->
    <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
    </el-form-item>
</el-form>
</template>

    
<script>
import assetAdd from './assetAdd.vue';
import userService from '@/api/user';
import departmentService from '@/api/depart';
import backButton from '@/components/BackButton/backButton.vue';
import assetDistributeApi from '@/api/asset-distribute';

export default {
    components: {
        assetAdd,
        backButton
    },
    data() {
        return {
            currentPage: 1,
            pageSize: 10,
            total: 0,
            tableData: [],
            showAssetDialog: false,
            applicants: [], // 存储申请人列表
            depart: '',
            ruleForm: {
                state: 0,
                applicationDate: null,
                applicationNum: '保存后自动生成',
                title: '',
                applicantId: '',
                distributeDate: null,
                distributeReason: '',
                remark: '',
                assetIds: []
            },
            rules: {
                // 验证规则...
                state: [{
                    required: true,
                    message: '请选择状态',
                    trigger: 'change'
                }],
                applicationDate: [{
                    required: true,
                    message: '请选择申请日期',
                    trigger: 'change'
                }],
                title: [{
                        required: true,
                        message: '请输入标题',
                        trigger: 'blur'
                    },
                    {
                        min: 3,
                        max: 50,
                        message: '标题长度在 3 到 50 个字符',
                        trigger: 'blur'
                    }
                ],
                applicantId: [{
                    required: true,
                    message: '请输入申请人ID',
                    trigger: 'blur'
                }],
                distributeDate: [{
                    required: true,
                    message: '请选择派发日期',
                    trigger: 'change'
                }],
                distributeReason: [{
                        required: true,
                        message: '请输入申请理由',
                        trigger: 'blur'
                    },
                    {
                        min: 10,
                        message: '派发理由不能少于10个字符',
                        trigger: 'blur'
                    }
                ]
            }
        };
    },
    methods: {
        indexMethod(index) {
            return (index + 1) + (this.currentPage - 1) * this.pageSize; // 返回从1开始的索引
        },
        handleSizeChange(newSize) {
            this.pageSize = newSize
        },
        handleData(assetIds) {
            if (Array.isArray(assetIds)) {
                if (assetIds.length === 0) {
                    return
                }
                assetDistributeApi.addClaimFixedDetail({
                        page: this.currentPage,
                        limit: this.pageSize,
                        assetIds: assetIds
                    })
                    .then(response => {
                        if (Array.isArray(response.data)) {
                            response.data.forEach(element => {
                                if (!this.tableData.some(item => item.id === element.id)) {
                                    this.tableData.push(element)
                                }
                            });
                        }
                    })
                    .catch(error => console.log(error))
            } else {
                console.error('assetIds is not an array:', assetIds);
            }
        },
        handleSelectionChange(selection) {
            this.ruleForm.assetIds = selection.map(item => item.id)
        },
        handleCurrentChange(newPage) {
            this.currentPage = newPage
        },
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                this.ruleForm.applicationNum = this.generateApplicationNum()
                if (this.ruleForm.applicationNum === '') {
                    return
                }
                if (this.ruleForm.assetIds.length === 0) {
                    alert("请选择资产")
                    return
                }
                if (valid) {
                    let assetDistributes = []
                    assetDistributes = this.ruleForm.assetIds.map(id => ({
                        state: this.ruleForm.state,
                        applicationDate: this.ruleForm.applicationDate,
                        applicationNum: this.ruleForm.applicationNum,
                        title: this.ruleForm.title,
                        applicantId: this.ruleForm.applicantId,
                        distributeDate: this.ruleForm.distributeDate,
                        distributeReason: this.ruleForm.distributeReason,
                        remark: this.ruleForm.remark,
                        assetId: id,
                        creatorId: this.getLoginUserId(),
                        flowId: 1,
                        currentNode: 1
                    }))
                    assetDistributeApi.batchAdd(assetDistributes)
                        .then(() => alert("数据添加成功！"))
                        .catch(error => console.log(error))
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
        addAsset() {
            this.showAssetDialog = true
        },
        removeAsset() {

        },
        deleteRow(index, rows) {
            rows.splice(index, 1);
        },
        fetchApplicants() {
            userService.findAll()
                .then(response => this.applicants = response.data)
                .catch(error => console.log(error))
        },
        fetchDeparts(applicantId) {
            departmentService.find(applicantId)
                .then(response => this.depart = response.data)
                .catch(error => console.log(error))

        },
        generateApplicationNum() {
            // 获取当前日期
            const currentDate = new Date();
            const year = currentDate.getFullYear();
            const month = (currentDate.getMonth() + 1).toString().padStart(2, '0');
            const day = currentDate.getDate().toString().padStart(2, '0');
            const datePart = `${year}${month}${day}`;

            // 生成随机六位数字
            const randomDigits = Math.floor(100000 + Math.random() * 900000).toString().padStart(6, '0');

            // 拼接生成applicationNum
            const applicationNum = `ORD${datePart}${randomDigits}`;

            return applicationNum;
        },
        getLoginUserId() {

            // 使用Vuex，可以这样获取：
            // return this.$store.state.userId;
        }
    }
};
</script>

    
<style scoped>
.base-info span {
    display: block;
    margin-bottom: 20px;
}

.el-form-item__label {
    font-weight: bold;
}
</style>
